package com.pansoft.openplanet.activity.child;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.DialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.zxing.qrcode.MipcaActivityCapture;
import com.efounder.chat.zxing.qrcode.QRCode;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.utilcode.util.ScreenUtils;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONObject;

import java.util.Random;

/**
 * 授权签名页面
 */
public class AuthorizationSignFragment extends DialogFragment implements View.OnClickListener {

    public static final String TAG = "AuthorizationSignFragment";

    private TextView title;
    private ImageView ivClose;
    private TextView tvTip1;
    private ImageView ivCode;
    private Button button;

    private ConstraintLayout clPage1;
    private ConstraintLayout clPage2;
    private ImageView ivBack;
    private EditText etWalletSign;
    private Button buttonEnter;
    private ImageView ivCode1;
    private String requestData;

    private String resultPublicKey;
    private String address;

    private CreateObserveListener listener;


    public static AuthorizationSignFragment newInstance(String address) {

        Bundle args = new Bundle();
        args.putString("address", address);
        AuthorizationSignFragment fragment = new AuthorizationSignFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public AuthorizationSignFragment() {
    }


    @Override
    public void onStart() {
        super.onStart();

        int screenHeight = ScreenUtils.getScreenHeight();
        getDialog().getWindow()
                .setLayout(WindowManager.LayoutParams.MATCH_PARENT, screenHeight * 3 / 5);
        getDialog().getWindow().setGravity(Gravity.BOTTOM);
        getDialog().setCanceledOnTouchOutside(true);
        getDialog().setCancelable(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.assets_dialog_fragment_authorization_sign, container, false);
        initView(rootView);
        initData();
        return rootView;
    }

    private void initData() {
        address = getArguments().getString("address");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "observeWallet");
        jsonObject.put("walletAddress", address);
        requestData = getRandomChar(10);
        jsonObject.put("data", requestData);

        Bitmap bm = QRCode.setQRcode(jsonObject.toString(), 800, 800);
        if (bm != null) {
            ivCode.setImageBitmap(bm);
        }


    }

    private void initView(View rootView) {
        title = (TextView) rootView.findViewById(R.id.title);
        ivClose = (ImageView) rootView.findViewById(R.id.iv_close);
        tvTip1 = (TextView) rootView.findViewById(R.id.tv_tip1);
        ivCode = (ImageView) rootView.findViewById(R.id.iv_code);
        button = rootView.findViewById(R.id.button_next);

        clPage1 = (ConstraintLayout) rootView.findViewById(R.id.cl_page1);
        clPage2 = (ConstraintLayout) rootView.findViewById(R.id.cl_page2);
        ivBack = (ImageView) rootView.findViewById(R.id.iv_back);
        etWalletSign = (EditText) rootView.findViewById(R.id.et_wallet_sign);
        buttonEnter = (Button) rootView.findViewById(R.id.button_enter);
        ivCode1 = rootView.findViewById(R.id.iv_code1);
        ivCode1.setOnClickListener(this);

        buttonEnter.setOnClickListener(this);
        button.setOnClickListener(this);
        ivClose.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        clPage2.setVisibility(View.GONE);
        clPage1.setVisibility(View.VISIBLE);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_close) {
            dismiss();
        } else if (id == R.id.button_next) {
            clPage1.setVisibility(View.GONE);
            clPage2.setVisibility(View.VISIBLE);

        } else if (id == R.id.iv_back) {
            clPage2.setVisibility(View.GONE);
            clPage1.setVisibility(View.VISIBLE);
        } else if (id == R.id.button_enter) {


            createOnserveWallet();

        } else if (id == R.id.iv_code1) {
            //跳转扫描二维码
            Intent intent = new Intent();
            intent.setClass(getActivity(), MipcaActivityCapture.class);
            intent.putExtra(MipcaActivityCapture.NEED_RESULT, "true");
            startActivityForResult(intent, 1);

        }
    }


    /**
     * 创建观察者钱包
     */
    private void createOnserveWallet() {
        if (resultPublicKey == null || "".equals(resultPublicKey)) {
            ToastUtils.showShort(R.string.open_planet_recovering_observe_wallet_fail);
            return;
        }
        if (listener != null) {
            listener.startCreate(address, resultPublicKey);
        }
        dismiss();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String msg = data.getStringExtra("scanResult");
                JSONObject jsonObject = JSONObject.fromObject(msg);

                String resultData = jsonObject.optString("data", "");
                if (!resultData.equals(requestData)) {
                    ToastUtil.showToast(getActivity(), ResStringUtil.getString(R.string.open_planet_asset_authorization_sign_data_not));
                    return;
                }
                resultPublicKey = jsonObject.optString("publicKey", "");
                etWalletSign.setText(resultPublicKey);
            }

        }
    }

    /**
     * 生成随机6位数,数字加字母
     *
     * @return
     */
    public static String getRandomChar(int number) {
        String s = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        Random r = new Random();
        String result = "";
        for (int i = 0; i < number; i++) {
            int n = r.nextInt(62);
            result += s.substring(n, n + 1);
        }
        return result;
    }

    public interface CreateObserveListener {
        void startCreate(String address, String publicKey);

    }

    public void setCreateObserveListener(CreateObserveListener listener) {
        this.listener = listener;
    }
}

